#include <CCfits/CCfits>

using namespace std;

int main(void);
int read(void);
void listpix(float **, int, int);

float **z;
char *arquivo = "test.fits";
int ncol, nrow;

int main(void) {

	return read();

}

void listpix(float **z, int rows, int cols) {

	int x,y;

	for (x = 0; x < rows; x++)
		for (y = 0; y < cols; y++)
			printf("%d. %d. %6.4f\n", y+1, x+1, z[x][y]);
	
}

int read(void) {

	int x, y, i;

	try {

		FITS *fin = new FITS(arquivo, Read, false);
		
		PHDU &image = fin->pHDU();

		if (image.axes() != 2) {
			cerr << "Erro: A imagem deve ter exatamente 2 dimensoes." << endl;
			return 1;
		}		
				
		valarray<float> contents;
		image.read(contents);

		nrow = (int)image.axis(1);
		ncol = (int)image.axis(0);

		fin->~FITS();

		// declara e aloca espaco para a matriz z
		z = (float **)calloc(nrow+1, sizeof(float *));
		for (x = 0; x < nrow; x++)
			z[x] = (float *)calloc(ncol+1, sizeof(float));

		if (z == NULL) {
			cerr << "Erro: Erro de alocacao de memoria." << endl;
			return 1;
		}
		
		for (x = y = i = 0; i < nrow * ncol; i++, y++) {
			if (y == ncol){
				x++;
				y = 0;
			}

			z[x][y] = contents[i];
		}

#ifdef __DEBUG__
		listpix(z, nrow, ncol);
#endif

	} catch(FitsException &) {

		return 1;
	
	}

	return 0;
}
